/*
 * Copyright (c) 2025 Li Auto Inc. and its affiliates
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef RTPS_BUILTIN__BUILTINREADER_HPP_
#define RTPS_BUILTIN__BUILTINREADER_HPP_

#include <memory>

#include <deps/common/InstanceHandle.h>

#include <history/ReaderHistory.h>
#include <history/ReaderListener.h>
#include <history/ITopicPayloadPool.h>
#include <history/PoolConfig.h>

namespace evbs {
namespace ertps {
namespace rtps {

using vbsutil::xmlparser::InstanceHandle_t;

/**
 * Keeps data of a builtin reader
 */
template <typename TReader>
struct BuiltinReader {
    ~BuiltinReader() { release(); }

    void release() {
        if (history_) {
            auto cfg = vbs::common::PoolConfig::from_history_attributes(history_->m_att);
            history_.reset();
            if (payload_pool_) {
                payload_pool_->release_history(cfg, true);
            }
        }

        listener_.reset();
    }

    void remove_from_history(const InstanceHandle_t& key) {
        history_->getMutex().lock();
        for (auto it = history_->changesBegin(); it != history_->changesEnd(); ++it) {
            if ((*it)->instanceHandle == key) {
                history_->remove_change_nts(*it);
                break;
            }
        }
        history_->getMutex().unlock();
    }

    //! Payload pool for the topic
    std::shared_ptr<vbs::common::ITopicPayloadPool> payload_pool_;
    //! History for the builtin reader
    std::unique_ptr<vbs::common::ReaderHistory> history_;
    //! Builtin RTPS reader
    TReader* reader_ = nullptr;
    //! Listener for the builtin RTPS reader
    std::unique_ptr<vbs::common::ReaderListener> listener_;
};

}  // namespace rtps
}  // namespace ertps
}  // namespace evbs

#endif  // RTPS_BUILTIN__BUILTINREADER_HPP_
